var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var routes = require('./routes/index');
var users = require('./routes/users');
var plaza = require('./routes/plaza');
var home = require('./routes/home');
var preview = require('./routes/preview');
var ppt = require('./routes/ppt');
var image = require('./routes/image');
var tg = require('./routes/tg');
var tg3 = require('./routes/tg3');
var design = require('./routes/design');
var font = require('./routes/font');
var print = require('./routes/print');
var payment = require('./routes/payment');
var callFunc = require('./routes/callFunc');
var CONFIG = require('../common/config');
//---------------------v5 begin----------------------
var v5Tg3 = require('./routes/v5/tg3.js');
var v5Users = require('./routes/v5/users.js');
var v5Print = require('./routes/v5/print.js');
var api4back = require('./routes/v5/api4back.js');
var activity = require('./routes/v5/activity.js');
var lab = require('./routes/v5/lab.js');
var wechat = require('./routes/v5/wechat.js');
//---------------------v5 end----------------------

//-----------------------third part begin------------------------
// var tpv1Orders = require('./routes/tp/v1/orders.js');
// var tpv1Users = require('./routes/tp/v1/users.js');
// var tpv1Goods = require('./routes/tp/v1/goods.js');
// var tpv1Document = require('./routes/tp/v1/document.js');
//-----------------------third part end------------------------

//-----------------------redis-lua part begin------------------------
var lua = require('./routes/lua.js');
//-----------------------redis-lua part end------------------------

//-----------------------yjx part begin------------------------
var yjx_v1_document = require('./yjx/v1/document');
var yjx_v1_order = require('./yjx/v1/order');
var yjx_v1_sundry = require('./yjx/v1/sundry');
var yjx_v1_user = require('./yjx/v1/user');
var yjx_v1_activity = require('./yjx/v1/activity');
var yjx_v1_api4back_api4back = require('./yjx/v1/api4back/api4back');
var yjx_v1_api4back_promoter = require('./yjx/v1/api4back/promoter');
var yjx_v1_api4back_company = require('./yjx/v1/api4back/company');
var yjx_v1_api4back_users = require('./yjx/v1/api4back/users');
var yjx_v1_api4back_financial = require('./yjx/v1/api4back/financial');

//-----------------------yjx part end------------------------


//-----------------------yjsc Platform begin------------------------

var yjsc_design_v1_AIPlugin = require('./yjscPlatform/design/v1/AIPlugin');
var yjsc_design_v1_designs = require('./yjscPlatform/design/v1/designs');
var yjsc_design_v1_sundry = require('./yjscPlatform/design/v1/sundry');
var yjsc_design_v1_users = require('./yjscPlatform/design/v1/users');

//-----------------------yjsc Platform end------------------------


//-----------------------yjsc begin------------------------
var yjsc_v2_document = require('./yjsc/v2/document');
var yjsc_v2_order = require('./yjsc/v2/order');
var yjsc_v2_sundry = require('./yjsc/v2/sundry');
var yjsc_v2_user = require('./yjsc/v2/user');
var yjsc_v2_api4back = require('./yjsc/v2/api4back');
//-----------------------yjsc end------------------------

// 小城
var mp = require('./mp/index');


require('body-parser-xml')(bodyParser);

//var Mongo = require('../common/mongo');
//var MAPILogModel = Mongo.MAPILogModel;


var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
// app.use(logger('dev'));
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));

app.use(cookieParser());

// 解决微信支付通知回调数据
app.use(bodyParser.xml({
  limit: '2MB',   // Reject payload bigger than 1 MB
  xmlParseOptions: {
    normalize: true,     // Trim whitespace inside text nodes
    normalizeTags: true, // Transform tags to lowercase
    explicitArray: false, // Only put nodes in array if >1
    //explicitRoot: false
  }
}));

if(CONFIG.DEBUG){
  app.use(session({
    secret: 'api-sercret',
    name: 'api-sname',     //这里的name指的是cookie的name,默认cookie的name是：connect.sid
    cookie: {maxAge: 24*60*60*1000},  //设置maxAge是80000ms,即80s后session 和相应的cookie失效过期
    resave: false,
    saveUninitialized: false,
    //store:new RedisStore({
    //  host:CONFIG.HOME_SESSION_REDIS_SERVER_DOMAIN,
    //  pass:CONFIG.HOME_SESSION_REDIS_SERVER_PASSWORD,
    //  port:CONFIG.HOME_SESSION_REDIS_SERVER_PORT,
    //  db:CONFIG.HOME_SESSION_REDIS_SERVER_DE_NUMBER,
    //  ttl:CONFIG.HOME_SESSION_REDIS_SERVER_TTL,
    //  prefix:CONFIG.HOME_SESSION_REDIS_SERVER_PREFIX,
    // })

  }));
}else {
  app.use(session({
    secret: 'api-sercret',
    name: 'api-sname',   //这里的name值指的是cookie的name,默认cookie的name是：connect.sid
    cookie: {maxAge:24*60*60*1000},  //设置maxAge是80000ms, 即80s后session和相应的cookie失效过期
    resave: false,
    saveUninitialized: false,
    store: new RedisStore({
      host:CONFIG.API_SESSION_REDIS_SERVER_DOMAIN,
      pass:CONFIG.API_SESSION_REDIS_SERVER_PASSWORD,
      port:CONFIG.API_SESSION_REDIS_SERVER_PORT,
      db:CONFIG.API_SESSION_REDIS_SERVER_DB_NUMBER,
      ttl:CONFIG.API_SESSION_REDIS_SERVER_TTL,
      //prefix:CONFIG.API_SESSION_REDIS_SERVER_PREFIX,
    })

  }));
}

app.use(express.static(path.join(__dirname, 'public')));


// 拦截放在 app.use('/', routes) 前面，可以拦截所有请求
app.use(function(req, res, next) {
    //if(CONFIG.DEBUG!=1 && req.originalUrl && req.originalUrl.indexOf('/ck')<0){ // release模式下记录API数据到mongodb
    //    var model = MAPILogModel({
    //        api_name: req.originalUrl,
    //        device:req.query.device || req.body.device,
    //        userId:req.query.userId || req.body.userId || 0
    //    });
    //    MAPILogModel.create(model, function(insErr, insRet){
    //        if (insErr) {
    //            console.log('api app.js ins Err: '+insErr);
    //        }
    //    });
    //}


    next();
});

app.use('/', routes);
// ------ 开启接口日志 --------
app.use(logger('dev'));
// ------ 开启接口日志 --------
app.use('/users', users);
app.use('/plaza',plaza);
app.use('/home',home);
app.use('/preview',preview);
app.use('/ppt',ppt);
app.use('/image',image);
app.use('/tg',tg);
app.use('/tg3',tg3);
app.use('/design',design);
app.use('/font',font);
app.use('/print',print);
app.use('/payment',payment);
app.use('/callFunc',callFunc);

//-------------------v5 begin--------------------------
app.use('/v5/tg3', v5Tg3);
app.use('/v5/users', v5Users);
app.use('/v5/print', v5Print);
app.use('/v5/api4back', api4back);
app.use('/v5/activity', activity);
app.use('/v5/lab', lab);
app.use('/v5/wechat', wechat);
//-------------------v5 end--------------------------

//-----------------------third part begin------------------------
// app.use('/tp/v1/orders', tpv1Orders);
// app.use('/tp/v1/users', tpv1Users);
// app.use('/tp/v1/goods', tpv1Goods);
// app.use('/tp/v1/document', tpv1Document);
//-----------------------third part end------------------------

//-----------------------redis-lua part begin------------------------
app.use('/lua', lua);
//-----------------------redis-lua part end------------------------

//-----------------------yjx begin ------------------------

app.use('/yjx/v1/document', yjx_v1_document);
app.use('/yjx/v1/order', yjx_v1_order);
app.use('/yjx/v1/sundry', yjx_v1_sundry);
app.use('/yjx/v1/user', yjx_v1_user);
app.use('/yjx/v1/activity', yjx_v1_activity);
app.use('/yjx/v1/api4back/api4back', yjx_v1_api4back_api4back);
app.use('/yjx/v1/api4back/promoter', yjx_v1_api4back_promoter);
app.use('/yjx/v1/api4back/company', yjx_v1_api4back_company);
app.use('/yjx/v1/api4back/users', yjx_v1_api4back_users);
app.use('/yjx/v1/api4back/financial', yjx_v1_api4back_financial);


//-----------------------yjx end ------------------------

//-----------------------yjsc Platform begin------------------------

app.use('/yjsc/yjscPlatform/design/v1/AIPlugin', yjsc_design_v1_AIPlugin);
app.use('/yjsc/yjscPlatform/design/v1/designs', yjsc_design_v1_designs);
app.use('/yjsc/yjscPlatform/design/v1/sundry', yjsc_design_v1_sundry);
app.use('/yjsc/yjscPlatform/design/v1/users', yjsc_design_v1_users);
//-----------------------yjsc Platform end------------------------

//-----------------------yjsc begin------------------------
app.use('/yjsc/v2/document', yjsc_v2_document);
app.use('/yjsc/v2/order', yjsc_v2_order);
app.use('/yjsc/v2/sundry', yjsc_v2_sundry);
app.use('/yjsc/v2/user', yjsc_v2_user);
app.use('/yjsc/v2/api4back', yjsc_v2_api4back);

//-----------------------yjsc end------------------------


app.use('/mp', mp);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    console.log(err);
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  console.log(err);
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

// global info
app.locals.global = {};
app.locals.global.api_sever_url ='http://'+CONFIG.API_SERVER_DOMAIN+':'+CONFIG.API_SERVER_PORT;
app.locals.global.upload_sever_url = 'http://'+ CONFIG.UPLOAD_SERVER_DOMAIN+':'+CONFIG.UPLOAD_SERVER_PORT;

module.exports = app;
